package br.com.credfaz.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import br.com.credfaz.dao.ClienteDAO;
import br.com.credfaz.model.Cliente;

public class JdbcClienteDAO implements ClienteDAO {
	
	private DataSource dataSource;
	private JdbcTemplate jdbcTemplateObject;
	
	
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
		this.jdbcTemplateObject = new JdbcTemplate(dataSource);
	}
	
	public void insert(Cliente cliente){
		 
		String sql = "INSERT INTO cliente " +
				"(idcliente, numcpfcnpj, nomereceita) VALUES (?, ?, ?)";
		Connection conn = null;
 
		try {
			conn = dataSource.getConnection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setLong(1, cliente.getIdcliente());
			ps.setString(2, cliente.getNumcpfcnpj());
			ps.setString(3, cliente.getNomereceita());
			ps.executeUpdate();
			ps.close();
 
		} catch (SQLException e) {
			throw new RuntimeException(e);
 
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {}
			}
		}
	}
	
	public Cliente findByClienteId(int clienteId){
		 
		String sql = "SELECT * FROM cliente WHERE idcliente = ?";
 
		Connection conn = null;
 
		try {
			conn = dataSource.getConnection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, clienteId);
			Cliente cliente = null;
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
//				cliente = new Cliente(
//					rs.getLong("idcliente"),
//					rs.getString("numcpfcnpj"), 
//					rs.getString("nomereceita")
//				);
			}
			
			rs.close();
			ps.close();
			return cliente;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			if (conn != null) {
				try {
				conn.close();
				} catch (SQLException e) {}
			}
		}
	}
	
	public List<Cliente> listClientes() {
		
	      String SQL = "select * from cliente";
	      
	      List<Cliente> clientes = jdbcTemplateObject.query(SQL, new ClienteMapper());
	      
	      return clientes;
	   }
	

}
